<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use think\facade\Cache;

class Wmp
{

	/**
	* 写日志方法
	*
	* @return
	*/
  private function cfg_write_logs( $request, $cookie, $companyId, $nickname, $username, $operType ) {
		$browser = new \Browser\Browser();
		Db::table('cfg_logs')->insert([
			'browser'=> $browser->getBrowser(),
			'device'=> $browser->getPlatform(),
			'referer'=> $request->header('referer'),
			'method'=> $request->method(),
			'url'=> $request->url(),
			'ip'=> $request->ip(),
			'cookie'=> $cookie,
			'companyId' => $companyId,
      'nickname' => $nickname,
      'user' => $username,
			'operType'=> $operType,
			'type'=> 1,
			'time'=> time() ]);
  }

	/**
	 * 判断小程序是否已登录
	 *
	 * @return
	 */
	private function isLogin($token)
	{
		if(empty($token)) {
			return false;
		}
		$cache = Cache::get($token);
		if(!is_array($cache) ) {
			return false;
		}
		if(!isset($cache['id'])){
			return false;
		}
		if(empty($cache['id'])){
			return false;
		}
		return $cache;
	}


	/**
	 * 微信小程序计划状态
	 *
	 * @return
	 */
	public function getStatus($userType, $status)
	{
		if($userType == 1) {
			if( $status == 21 ) {
				return 1;
			}
			return 0;
		}

		if( $status == 0 ) {
			return 1;
		}

		return 0;
	}

	/**
	 * 微信小程序计划接口
	 *
	 * @return
	 */
	public function plan(Request $request)
	{
		$token = $request->param('token', '', 'trim');
		$cache = $this->isLogin($token);
		if(!$cache) {
			return json(['msg' => '您还没有登录,请登录后再试!', 'access_token' => null, 'code' => 403]);
		}
		$expand = Db::table('cfg_expand')->field('id, userType, userId, username, balance')->where('companyId', $cache['companyId'])->select()->toArray();
		foreach($expand as &$value ) {
			$value['username'] = $value['username'] . ' - 余额: ' . $value['balance'];
		}
		$campaign = Db::table('cfg_campaign')->field('id, userType, userId, status, bazaarId, campaignName')->where('companyId', $cache['companyId'])->select()->toArray();
		foreach($campaign as &$value ) {
			$value['cstatus'] = $this->getStatus($value['userType'], $value['status']);
			$value['bazaarName'] = Db::table('cfg_bazaar')->where('id', $value['bazaarId'])->value('name');
		}
		return json(['msg' => '操作成功!', 'data' => [ 'expand' => $expand, 'campaign' => $campaign ], 'code' => 1]);
	}

	/**
	 * 微信小程序操作计划
	 *
	 * @return
	 */
	public function pause(Request $request)
	{
		$token = $request->param('token', '', 'trim');
		$cache = $this->isLogin($token);
		if(!$cache) {
			return json(['msg' => '您还没有登录,请登录后再试!', 'access_token' => null, 'code' => 403]);
		}
		$id = $request->param('id', '', 'trim');
		if(empty($id)) {
			return json(['msg' => '操作成功', 'code' => 1]);
		}
		$pause = false;
		$status = $request->param('status', '', 'trim');
		if($status == 2) {
			$pause = true;
		}

		$campaign = Db::table('cfg_campaign')->where('id', $id)->find();
		if(!isset($campaign['userId'])) {
			return json(['msg' => '计划不存在', 'code' => 1]);
		}

		$expand = Db::table('cfg_expand')->where('userid', $campaign['userId'])->find();
		if(!isset($expand['id'])) {
			return json(['msg' => '账户不存在', 'code' => 1]);
		}
		if( $expand['userType'] == 1 ) {
			$request = doPostRequest('https://api.baidu.com/json/sms/service/CampaignService/updateCampaign', json_encode([
					'header'=>['username'=> $expand['username'], 'password'=> $expand['password'], 'token'=> $expand['token'] ],
					'body'=> [
						'campaignTypes'=>[
							[
								"campaignId"=> $campaign['campaignId'],
								"pause"=> $pause,
							]
						]
					]
				]));
			if(empty($request)) {
				return json(['msg' => '竞价操作失败', 'code' => 1]);
			}
			$result = json_decode ($request, true);
			if(!isset($result['header']['desc'])){
				return json(['msg' => '竞价操作失败', 'code' => 1]);
			}
			if(!isset($result['header']['desc'])) {
				return json(['msg' => '竞价操作失败', 'code' => 1]);
			}
			if($result['header']['desc'] == 'success') {
				$campaign = doPostRequest('https://api.baidu.com/json/sms/service/CampaignService/getCampaign', json_encode([
					'header'=>['username'=> $expand['username'], 'password'=> $expand['password'], 'token'=> $expand['token'] ],
					'body'=> [
						"campaignFields"=> [
								"campaignId",
								"campaignName",
								"budget",
								"negativeWords",
								"exactNegativeWords",
								"status",
						],
						"mobileExtend"=> 1,
						"adType"=> 0
					]
				]));
				if( $campaign ) {
					$campaignJson = json_decode ($campaign, true);
					if( isset($campaignJson['body']['data'][0]) ){
						Db::name('cfg_campaign')->where('campaignId', $campaignJson['body']['data'][0]['campaignId'])->update(['status' => $campaignJson['body']['data'][0]['status']]);
					}
				}
				return json(['msg' => '竞价操作成功', 'code' => 1]);
			}
			return json(['msg' => '竞价操作失败', 'code' => 1]);
		}
		$request = doPostRequest('https://api.baidu.com/json/feed/v1/CampaignFeedService/updateCampaignFeed', json_encode([
			'header'=>['username'=> $expand['username'], 'password'=> $expand['password'], 'token'=> $expand['token'] ],
			'body'=> [
				'campaignFeedTypes'=>[
					[
						"campaignFeedId"=> $campaign['campaignId'],
						"pause"=> $pause
					]
				]
			]
		]));
		if(empty($request)) {
			return json(['msg' => '信息流操作失败', 'code' => 1]);
		}
		$result = json_decode ($request, true);
		if(!isset($result['header']['desc'])){
			return json(['msg' => '信息流操作失败', 'code' => 1]);
		}
		if(!isset($result['header']['desc'])) {
			return json(['msg' => '信息流操作失败', 'code' => 1]);
		}
		if($result['header']['desc'] == 'success') {
			$campaignFeed = doPostRequest('https://api.baidu.com/json/feed/v1/CampaignFeedService/getCampaignFeed', json_encode([
				'header'=>['username'=> $expand['username'], 'password'=> $expand['password'], 'token'=> $expand['token'] ],
				'body'=> [
					"campaignFeedFields"=> [
							"status"
					]
				]
			]));
			if($campaignFeed) {
				$campaignJson = json_decode ($campaignFeed, true);
				if( isset($campaignJson['body']['data'][0]) ){
					Db::name('cfg_campaign')->where('campaignId', $campaignJson['body']['data'][0]['campaignFeedId'])->update(['status' => $campaignJson['body']['data'][0]['status']]);
				}
			}
			return json(['msg' => '信息流操作成功', 'code' => 1]);
		}
	  return json(['msg' => '信息流操作失败', 'code' => 1]);
	}

	/**
	 * 微信小程序操作客服
	 *
	 * @return
	 */
	public function status(Request $request)
	{
		$token = $request->param('token', '', 'trim');
		$cache = $this->isLogin($token);
		if(!$cache) {
			return json(['msg' => '您还没有登录,请登录后再试!', 'access_token' => null, 'code' => 403]);
		}
		$id = $request->param('id', '', 'trim');
		if(empty($id)) {
			return json(['msg' => '操作成功', 'code' => 1]);
		}
		$status = $request->param('status', '', 'trim');
		if($status == 2){
			$status = 0;
		}
		Db::name('cfg_service')->where('companyId', $cache['companyId'])->where('id', $id)->update(['status' => $status]);
		return json(['msg' => '操作成功', 'code' => 1]);
	}

	/**
	 * 微信小程序客服接口
	 *
	 * @return
	 */
	public function service(Request $request)
	{
		$token = $request->param('token', '', 'trim');
		$cache = $this->isLogin($token);
		if(!$cache) {
			return json(['msg' => '您还没有登录,请登录后再试!', 'access_token' => null, 'code' => 403]);
		}
		$zone = Db::table('cfg_zone')->field('id,platform,name')->where('companyId', $cache['companyId'])->select()->toArray();
		$service = Db::table('cfg_service')->field('id, zoneid, nickname, status, wechat, number')->where('companyId', $cache['companyId'])->select()->toArray();
		return json(['msg' => '操作成功!', 'data' => [ 'zone' => $zone, 'service' => $service ], 'code' => 1]);
	}

	/**
	 * 微信小程序登录接口
	 *
	 * @return
	 */
	public function index(Request $request)
	{
		$username = $request->param('username', '', 'trim');
		$password = $request->param('password', '', 'trim');
		$token = md5( time() . mt_rand(100000, 999999) );

		if( empty($username) ) {
			return json(['msg' => '用户名不能为空!', 'access_token' => null, 'code' => 403]);
		}

		if( empty($password) ) {
			return json(['msg' => '密码不能为空!', 'access_token' => null, 'code' => 403]);
		}

		$query = Db::table('cfg_user')->field('id, companyId, username, password, company, level, nickname, status, expires, loginip, logintime, logincity')->where('username', $username)->find();
		if (!isset($query['id'])) {
			return json(['msg' => '用户名或密码错误!', 'access_token' => null, 'code' => 403]);
		}

		if (!password_verify($password, $query['password'])) {
			$this->cfg_write_logs($request, $token, $query['companyId'], $query['nickname'], $query['username'], 1);
			return json(['msg' => '用户名或密码错误!', 'access_token' => null, 'code' => 403]);
		}

		if( $query['status'] <> 1 ) {
			$this->cfg_write_logs($request, $token, $query['companyId'], $query['nickname'], $query['username'], 1);
			return json(['msg' => '账户以被锁定, 请联系管理员!', 'access_token' => null, 'code' => 403]);
		}

		$company = $query['company'];
		$expires = $query['expires'];

		if( $query['expires'] > '2000-01-01 08:00:00') {
			if( $query['level'] == 2 ) {
				if( date('Y-m-d H:i:s') >= $query['expires'] ){
					return json(['msg' => '账户已过期, 请联系管理员!', 'access_token' => null, 'code' => 403]);
				}
			}
			if( $query['level'] == 3 ) {
				$subquery = Db::table('cfg_user')->field('id, company, expires')->where('companyId', $query['companyId'])->where('level', 2)->find();
				if( !isset($subquery['id']) ) {
					return json(['msg' => '主账号存在异常, 请联系管理员!', 'access_token' => null, 'code' => 403]);
				}
				if( date('Y-m-d H:i:s') >= $subquery['id'] ) {
					$company = $subquery['company'];
					$expires = $subquery['expires'];
					return json(['msg' => '主账户已过期, 请联系管理员!', 'access_token' => null, 'code' => 403]);
				}
			}
		}

		if( $query['loginip'] ) {
			$temp1 = explode('.', $request->ip());
			$temp2 = "{$temp1[0]}.{$temp1[1]}.{$temp1[2]}";
			if( stripos($query['loginip'], $temp2) === false ) {
				$this->cfg_write_logs($request, $token, $query['companyId'], $query['nickname'], $query['username'], 1);
				return json(['msg' => '未授权IP禁止登录, 请联系管理员!', 'access_token' => null, 'code' => 403]);
			}
		}

		if( $query['logintime'] ) {
			$temp1 = explode('-', $query['logintime']);
			if(date('G') < $temp1[0] || date('G') > $temp1[1] ){
				$this->cfg_write_logs($request, $token, $query['companyId'], $query['nickname'], $query['username'], 1);
				return json(['msg' => '当前时段未授权登录, 请联系管理员!', 'access_token' => null, 'code' => 403]);
			}
		}

		if( $query['logincity'] ) {
			$logincity = explode(',', $query['logincity']);
			$address = new \Net\IpLocation( app()->getRootPath() . 'data' . DIRECTORY_SEPARATOR . 'qqwry.dat');
			$addressName = $address->getAddrName($request->ip());
			foreach ($logincity as $value) {
				if( stripos($addressName, $value) !== false ) {
					$this->cfg_write_logs($request, $token, $query['companyId'], $query['nickname'], $query['username'], 1);
					return json(['msg' => '不在常用登录地登录, 请回到常用登录地登录!', 'access_token' => null, 'code' => 403]);
				}
			}
		}

		Cache::set($token, ['id'=> $query['id'], 'companyId'=> $query['companyId'], 'level'=> $query['level'],
		  'username'=> $query['username'], 'nickname'=> $query['nickname'], 'company'=> $company ? $company : '未设置', 'expires'=> $expires ? $expires : '永不过期'], 30 * 86400);

		Db::name('cfg_user')->where('id', $query['id'])->where('companyId', $query['companyId'])->update([ 'lasttime' => time(), 'lastip' => $request->ip() ]);

		$this->cfg_write_logs($request, $token, $query['companyId'], $query['nickname'], $query['username'], 0);

		return json(['msg' => '登录成功!', 'access_token' => $token, 'code' => 0, 'token_type' => 'Bearer']);

	}

}
